import axios from "axios"
import Cookie from 'js-cookie';
import router from 'router/main.js';
import * as API_TYPES from './api-types';
import store from '@/store/index'
import * as types from '@/store/mutation-types'
// 需要授权的接口数组
const authApis = [
	// API_TYPES.APPLY,
];
import {
	sessionSetItem,
	sessionGetItem,
	sessionRemoveItem
} from 'util/index.js';
import {
	Toast,
	Dialog
} from 'vant';

import {
	getAuth
} from 'util/getAuth.js';

// 创建axios 实例

const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_SERVICE_API,
	timeout: 10000, // 请求超时时间
})
// request 拦截器
service.interceptors.request.use(
	config => {
		// 显示请求loading
		Toast.loading({
			message: '请求中...',
			forbidClick: true,
			loadingType: 'spinner'
		});
		// 每次请求都会有一个取消请求的方法
		let Cancel = axios.CancelToken; // 产生一个请求令牌
		config.cancelToken = new Cancel(function (c) {
			// vuex
			store.commit(types.PUSH_TOKEN, c); // 订阅
		});

		// 这里可以自定义一些config 配置
		const token = sessionGetItem('token');
		console.log(`request拦截器中的token${token}`);
		let url = config.url
		if (token) {
			config.headers['x-token'] = token;
		} else if (authApis.includes(url)) {
			console.warning('接口需要权限' + url + '请先获取授权');
		}
		return config
	},
	error => {
		//  这里处理一些请求出错的情况
		Promise.reject(error)
	}
)

// response 拦截器
service.interceptors.response.use(
	response => {
		const res = response.data;
		// 手动清除请求loading
		Toast.clear();
		let code = res.code;
		if (code == '0000') {
			return res;
		} else {
			if (code == '9001') {
				// token过期或token不存在
				router.replace({
					path: '/login',
					query: {
						fromRouterPath: router.currentRoute.fullPath
					}
				})
				// 这是微信静默登录的逻辑
				// sessionRemoveItem('token');
				// console.log(`当前路由${router.currentRoute.fullPath}`);
				// let redirect = router.currentRoute.fullPath;
				// getAuth(redirect);


			} else if (code === '9800') {
				// 缺少参数返回的就是9800

			} else if (code === '1004') {
				// 没有注册
				router.replace({
					path: '/register',
					query: {
						fromRouterPath: router.currentRoute.fullPath
					}
				})
			} else if (code == '9999' || code == '9998') {
				router.push({
					path: 'error',
					query: {
						message: res.message
					}
				})
			} else {
				return res;
			}
		}
	},
	error => {
		// 手动清除请求loading
		Toast.clear();
		router.push({
			path: 'error',
			query: {
				message: error.response&&error.response.data.message
			}
		})
		return Promise.reject(error)
	}
)

export default service;
